package com.jspgou.cms.action.member;

import static com.jspgou.cms.Constants.MEMBER_SYS;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.UserMng;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;
import com.jspgou.cms.dao.OrderDao;
import com.jspgou.cms.entity.MemberCoupon;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.manager.MemberCouponMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ShopMemberMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.cms.web.threadvariable.MemberThread;

/**
 * 会员中心Action
 * 
 * @author liufang
 * 
 */
@Controller
public class ShopMemberAct {
	private static final Logger log = LoggerFactory.getLogger(ShopMemberAct.class);

	/**
	 * 会员中心页
	 */
	public static final String MEMBER_CENTER = "tpl.memberCenter";
	public static final String MEMBER_PORTRAIT = "tpl.memberPortrait";
	/**
	 * 会员信息修改页
	 */
	public static final String MEMBER_PROFILE = "tpl.memberProfile";
	/**
	 * 会员密码修改页
	 */
	public static final String MEMBER_PASSWORD = "tpl.memberPassword";
	
	/**
	 * 会员中心页
	 * 
	 * 如果没有登录则跳转到登陆页
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/shopMember/index.jspx", method = RequestMethod.GET)
	public String index(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null||member.getIsEmployee()){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		BigDecimal money=dao.getMemberMoneyByYear(member.getId());
		Integer orders[] = dao.getOrderByMember(member.getId());
		List<MemberCoupon> list=couponMng.getList(member.getId());
		model.addAttribute("couList", list);
		model.addAttribute("orders", orders);
		model.addAttribute("money", money);
		model.addAttribute("historyProductIds", "");
		Cookie[] cookie = request.getCookies();
		for(int i=0;i<cookie.length;i++){
			if(cookie[i].getName().equals("shop_record")){
				String str = cookie[i].getValue();
				model.addAttribute("historyProductIds", str);
				break;
			}
		}
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				MEMBER_CENTER), request);
	}
	
	/**
	 * 个人资料输入页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/shopMember/profile.jspx", method = RequestMethod.GET)
	public String index(String cl,Integer flag,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null||member.getIsEmployee()){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		model.addAttribute("member", member);
		model.addAttribute("cl", cl);
		model.addAttribute("uploadRoot", web.getUploadUrl());
		if(flag!=null){
			model.addAttribute("flag", flag);
		}else{
			model.addAttribute("flag",1);
		}

		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				MEMBER_PROFILE), request);
	}
	
	/**
	 * 个人资料提交页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/shopMember/profile.jspx", method = RequestMethod.POST)
	public String profileSubmit(String cl,ShopMember bean, Long groupId,
			Integer flag,
			HttpServletRequest request,HttpServletResponse response,ModelMap model) {
		bean = manager.update(bean, groupId);
		log.info("ShopMember update infomation: {}", bean.getUsername());
		return index(cl,flag,request,response,model);
	}

	/**
	 * 密码修改输入页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/shopMember/pwd.jspx", method = RequestMethod.GET)
	public String passwordInput(String cl,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopFrontHelper.setCommonData(request, model, web);
		model.addAttribute("email", CmsUtils.getMember(request).getEmail());
		model.addAttribute("historyProductIds", "");
		model.addAttribute("cl", cl);
		Cookie[] cookie = request.getCookies();
		for(int i=0;i<cookie.length;i++){
			if(cookie[i].getName().equals("shop_record")){
				String str = cookie[i].getValue();
				model.addAttribute("historyProductIds", str);
				break;
			}
		}
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				MEMBER_PASSWORD), request);
	}

	/**
	 * 密码修改提交页
	 * 
	 * @param origPwd
	 *            原始密码
	 * @param newPwd
	 *            新密码
	 * @param email
	 *            邮箱
	 * @param nextUrl
	 *            下一个页面地址
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/shopMember/pwd.jspx", method = RequestMethod.POST)
	public String passwordSubmit(String origPwd, String newPwd, String email,
			String nextUrl, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Long userId = member.getMember().getUser().getId();
		WebErrors errors = validatePassword(userId, email, newPwd, member
				.getEmail(), origPwd, request);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		userMng.updateUser(userId, newPwd, email);
		log.info("ShopMember update password: {}", member.getUsername());
		return FrontHelper.showSuccess("global.success", nextUrl, web, model,
				request);
	}

	/**
	 * 验证密码是否正确
	 * 
	 * @param origPwd
	 *            原密码
	 * @param request
	 * @param response
	 */
	@RequestMapping("/shopMember/checkPwd.jspx")
	public void checkPwd(String origPwd, HttpServletRequest request,
			HttpServletResponse response) {
		ShopMember member=CmsUtils.getMember(request);
		Long userId = member.getMember().getUser().getId();
		boolean pass=userMng.isPasswordValid(userId, origPwd);
		ResponseUtils.renderJson(response, pass ? "true" : "false");
	}
	
	@RequestMapping(value="/shopMember/portrait.jspx",method=RequestMethod.GET)
	public String portrait(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=MemberThread.get();
		if(member == null){
			return "redirect:../login.jspx";
		}
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MEMBER_PORTRAIT), request);
	}
	
	/**
	 * 会员更改图像
	 * 
	 * @param memberId
	 *           会员ID
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/updateAvatar.jspx", method = RequestMethod.POST)//会员更改图像
	public String updateAvatar(String picPaths,HttpServletRequest request,HttpServletResponse response,
//			@RequestParam(value = "avatar", required = false) MultipartFile file,
			ModelMap model){
		Website web = SiteUtils.getWeb(request);
		ShopMember member=MemberThread.get();
		if(member == null){
			return "redirect:../login.jspx";
		}
//		ShopMember bean = manager.findById(memberId);
		member.setAvatar(picPaths);
		manager.update(member);
		return "redirect:shopMember/index.jspx";
	}
	
	private WebErrors validatePassword(Long userId, String email,
			String newPwd, String origEmail, String origPwd,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (!StringUtils.isBlank(newPwd)
				&& errors.ifOutOfLength(newPwd, "password", 3, 32)) {
			return errors;
		}
		if (!userMng.isPasswordValid(userId, origPwd)) {
			errors.addErrorCode("error.passwordInvalid");
		}
		if (errors.ifNotEmail(email, "email", 100)) {
			return errors;
		}
		if (!email.equals(origEmail) && userMng.emailExist(email)) {
			errors.addErrorCode("error.emailExist");
			return errors;
		}
		return errors;

	}

	@Autowired
	private OrderDao dao;
	@Autowired
	private UserMng userMng;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private ShopMemberMng manager;
	@Autowired
	private MemberCouponMng couponMng;
}
